package com.gainloop.Data;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;

import com.gainloop.Api.Entity.Session;
import com.gainloop.Api.Entity.User;

public class Registry
{
	private static final String PREFS_NAME = "gainloog-registry";

	private static final String SESSION_KEY = "session-json";

	static private Registry _instance = null;
	
	private static Registry getInstance()
	{
		if(_instance == null) {
			throw new RuntimeException("Please init Registry first");
		}
		
		return _instance;
	}
	
	public static void Init(Context context)
	{
		if(_instance != null) {
			return;
//			throw new RuntimeException("Registry already init");
		}
		_instance = new Registry(context);
	}
	
	private SharedPreferences settings;

	private User user = null;
	private Session session = null;
	
	private Registry(Context context)
	{
		settings = context.getSharedPreferences(PREFS_NAME, 0);
		
		String json = settings.getString(SESSION_KEY, null);
		if(json != null) {
			try {
				session = Session.fromObject(new JSONObject(json), Session.class);
			} catch (JSONException e) {
				e.printStackTrace();
				session = null;
			}
		}
	}
	
	static public User GetUser()
	{
		return getInstance().user;
	}
	
	static public void SetUser(User user)
	{
		getInstance().user = user;
	}
	
	static public void SetSession(Session session)
	{
		Registry reg = getInstance();
		
		reg.session = session;
		String json;
		try {
			json = session != null ? session.toObject().toString() : null;
		} catch (JSONException e) {
			e.printStackTrace();
			json = null;
		}
		
		SharedPreferences.Editor editor = reg.settings.edit();
		editor.putString(SESSION_KEY, json);
		editor.commit();
	}
	
	static public Session GetSession()
	{
		return getInstance().session;
	}
	
}
